package com.wx.Annotation;


import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 容器类
 * @author: wangxun
 * @createDate: 2021/12/27
 * @version: 1.0
 */
@Slf4j
public class MyContainer {

    static Map container = new HashMap<Class<?>, Object >(16);

    /**
     * 根据类镜像对象 创建对象
     * @param cls  类镜像对象
     * @return T
     * @author Wang.xun
     * @date 2021/12/27 15:43
     */
    public static <T>  T newInstance(Class<T> cls) throws InstantiationException, IllegalAccessException {
        log.info("获取属性");
        Field[] declaredFields = cls.getDeclaredFields();
        T clsObject = cls.newInstance();
        for (Field field : declaredFields) {

            if(!field.isAccessible()){
                field.setAccessible(true);
            }

            log.info("判断是否是注入的类型");
            WxInject annotation = field.getAnnotation(WxInject.class);
            if(annotation != null){
                Class<?> fieldClsType = field.getType();
                WxSingleton wxSingleton = fieldClsType.getAnnotation(WxSingleton.class);
                Object fieldObject = null;
                if(wxSingleton == null){
                    log.info("不是单例模式，那么就创建对象");
                    fieldObject = fieldClsType.newInstance();
                }else{
                    fieldObject = container.get(fieldClsType);
                    if(fieldObject == null){
                        log.info("缓存中没有对象，那么就创建对象，并保存");
                        fieldObject = fieldClsType.newInstance();
                        container.put(fieldClsType, fieldObject);
                    }
                }

                field.set(clsObject,fieldObject);
            }
        }
        return clsObject;
    }
}
